package com.hxzy.controller;

import com.google.common.net.HttpHeaders;
import com.hxzy.pojo.Admin;
import com.hxzy.pojo.Result;
import com.hxzy.pojo.StatusCode;
import com.hxzy.service.AdminService;
import com.hxzy.util.JwtUtil;
import com.hxzy.util.TokenDecode;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.SecretKey;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private AdminService adminService;

    @RequestMapping("/add")
    public Result addAdmin( Admin admin ,HttpServletRequest request) {
        boolean b = adminService.addAdmin(admin);
        if (b){
            Cookie[] cookies = request.getCookies();
            String mytoken = cookies[1].getValue();
            System.out.println(mytoken);


            return new Result(true, StatusCode.OK,"插入成功！",b);
        }
        return new Result(false,StatusCode.ERROR,"插入失败",b);
    }

    @RequestMapping("/login")
    //@PreAuthorize("#admin.name.equals('lhc')")
    public Result login(Admin admin, HttpServletResponse response, HttpServletRequest request){

        boolean login = adminService.login(admin);
        if (login){
            Map<String,Object> info = new HashMap<>();
            info.put("username",admin.getName());
            String token = JwtUtil.createJWT(UUID.randomUUID().toString(), admin.getName(), null);


            info.put("token",token.replace(".",""));

            Cookie cookie = new Cookie("myToken",token);
            response.addCookie(cookie);



            return new Result(true,StatusCode.OK,"登录成功",info);
        }
        return new Result(true,StatusCode.LOGINERROR,"登录失败",null);
    }

}
